import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserInfo, UserToken } from '../../shared/modes';
import { LocalstoreService } from '../../shared/services';
import { map, catchError } from 'rxjs/operators';
import { ResetPassword } from '../components/reset-password/reset-password.model';
import { of } from 'rxjs/observable/of';

@Injectable()
export class UserService {

  constructor(
    private http: HttpClient,
    private localstorage: LocalstoreService
  ) { }

  updateProfile(userId: string, userInfo: UserInfo): Observable<UserInfo> {
    const userToken: UserToken = this.localstorage.getItem('USER_TOKEN');
    return this.http
      .patch(`/platform/api/users/${userId}?access_token=${userToken.id}`, userInfo)
      .pipe(
        map((userInfo: UserInfo) => userInfo),
        catchError((error: HttpErrorResponse) => Observable.throw(error.error.error))
      );
  } 

  resetPassword(data: ResetPassword): Observable<any> {
    const userToken: UserToken = this.localstorage.getItem('USER_TOKEN');
    return this.http
      .post(`/platform/api/users/change-password?access_token=${userToken.id}`, data)
      .pipe(
        map(result => result),
        catchError((error: HttpErrorResponse) => Observable.throw(error.error.error))
      );
  }

}
